//index.js
const utils = require("../../utils/utils.js");
const biz = require("../../utils/bizUtils.js");
const listUtil = require("../../utils/listUtil.js");
const session = require("../../utils/session.js");
const toast = require("../../utils/toasts.js");
const wxm = require("../../utils/wechat_modules.js");
const com = require("../../utils/commonRequest.js");

import {
  req,
  cut_add
} from "../../utils/api.js";

//获取应用实例
const app = getApp()
const globalData = app.globalData;

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    list: [],
    hidden: true,
    scrollTop: 0,
    scrollHeight: 0,
    title: '',
    keyword: null,
    catId: null,
    orderRule: 'HOT',
    waiting: true,
    share_modal: false,
    noMore: false,
    banners: ['https://img.lingxing.site/jx/banner400_3_1.png'],
    isIphoneX: globalData.isIphoneX,
    showAllStaffs: false,
    flowStr:'选择教练->支付订金->到驾校支付尾款->学车->考试->拿到驾照->评价服务。\n注：订金在支付尾款前可全额退款，安全无忧。'
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function(options) {
    var that = this;
    wx.getSystemInfo({
      success: function(res) {
        console.info(res.windowHeight);
        that.setData({
          scrollHeight: res.windowHeight
        });
      }
    });

    if (options) {
      if (options.id) {
        this.setData({
          id: options.id
        });
      }

      if (options.from) {
        this.setData({
          from: options.from
        })
      }


      if (options.salesId) {
        this.setData({
          salesId: options.salesId
        })
        if (options.salesName) {}
      }

      if (options.index) {
        this.setData({
          index: options.index
        });
      }

      if (options.type) {
        this.setData({
          type: options.type,
        })
      }
    }
    this.refresh();
  },
  refreshMe: function(usr) {
    this.setData({
      user: usr
    });
    toast.showLoading();

    this.getData();
    this.getRates();
  },
  onShow: function() {},
  onShareAppMessage: function(res) {
    return wxm.commonProductShare(this, this.data.obj);

  },
  notExist:function() {
    wxm.showModal({
      title: '课程不存在',
      content: '你查找的课程不存在或已经下架',
      hideCancel: true,
      isIt: (true)
    }).then(() => {
      wx.navigateBack({

      })
      return;
    }).catch(() => { });
    return;
  },
  getData() {
    var id = this.data.id;
    if (!id) {
      this.notExist();
      return;
    }

    var that = this;
    req('/product/jxDetail', {
      id: id,
      withActivity: true
    }).then(res => {
      // console.log(res);
      if (res.success) {
        var obj = res.result;
        if (!obj || obj.status!='SALE') {
          this.notExist();
          return;
        }

        obj.rateScore = biz.rateScore(obj.totalRateScore, obj.totalRateCount);
        obj.rates = biz.rates(obj.rateScore);
        obj.rateTip = obj.rateScore + '分';
        if (!obj.rateScore) {
          obj.rateTip = '无评分';
        }
        
        obj.addressStr = biz.addressStr(obj);
        obj.bizTime = obj.openTime + '-' + obj.closeTime;

        that.setData({
          obj
        });
        this.getSeller();
        this.getStaffs();
      } else {
        toast.show(res.errorMsg);
      }
    });
  },
  getSeller() {
    var id = this.data.obj.sellerId;
    var that = this;
    req('/seller/jxDetail', {
      id: id
    }).then(res => {
      // console.log(res);
      if (res.success) {
        var obj = res.result;
        obj.addressStr = biz.addressStr(obj);
        obj.bizTime = obj.openTime + '-' + obj.closeTime;
        that.setData({
          seller:obj
        });
        that.getWorks();
      } else {
        toast.show(res.errorMsg);
      }
    });
  },
  getStaffs() {
    var id = this.data.obj.sellerId;
    var that = this;
    req('/seller/queryStaff', {
      sellerId: id,
      pageNo: 1,
      pageSize: 20
    }).then(res => {
      // console.log(res);
      if (res.success) {
        var list = res.result.list;
        var staffsCount = res.result.page.totalRecords;
        if (list) {
          for (var i = 0; i < list.length; i++) {
            var item = list[i];
            item.driveTimeStr = utils.calAge(item.driveTime);
            item.teachTimeStr = utils.calAge(item.teachTime);
            item.des = item.teachTimeStr + '年教龄';
          }
          that.setData({
            staffs: list,
            staffsCount
          })
        }
      } else {}
    });
  },
  getRates() {
    var id = this.data.id;
    var that = this;
    req('/rate/query', {
      productId: id,
      pageNo: 1,
      pageSize: 10
    }).then(res => {
      // console.log(res);
      if (res.success) {
        var list = res.result.list;
        if (list) {
          var ratesCount = res.result.page.totalRecords;
          for (var i = 0; i < list.length; i++) {
            var item = list[i];
            item.timeStr = utils.tf('yyyy-M-d', item.createdTime);
            item.rates = biz.rates(item.scoreall);
            var score = item.scoreall;
            if (!item.content) {
              if (score > 3) {
                item.content = '强烈推荐！';
              } else if (score == 3) {
                item.content = '一般般！';
              } else {
                item.content = '体验差不推荐！';
              }
            }
          }
          that.setData({
            rates: list,
            ratesCount
          })
        }
      } else {}
    });
  },
  pushFormSubmit: function(e) {
    console.log(e);
    console.log("formId:" + e.detail.formId);
    com.saveFormId(e);
  },
  gotoMap: function() {
    var obj = this.data.seller;
    biz.gotoMap({
      title: obj.name,
      lat: obj.lat,
      lng: obj.lng,
      address: obj.addressStr
    });
  },
  tel: function() {
    wxm.makePhoneCall(this.data.seller.tel);
  },
  showAllStaffs: function() {
    var showAllStaffs = this.data.showAllStaffs;
    this.setData({
      showAllStaffs: !showAllStaffs
    })
  },
  gotoSellerDetail:function() {
    var seller = this.data.seller;
    wx.navigateTo({
      url: '/pages/sellerDetail/sellerDetail?id='+seller.id,
    })
  },
  back:function() {
    wxm.back(this);
  },
  buy:function() {
    wx.navigateTo({
      url: '/pages/submitOrder/submitOrder?id='+this.data.id,
    })
  },
  gotoCut: function () {
    var that = this;
    toast.showLoading();
    var param = {
      id: that.data.obj.activityId,
    };

    cut_add(param).then(res => {
      if (res.success) {
        var obj = res.result;
        if (obj.id) {
          wx.navigateTo({
            url: '/pages/cutDetail/cutDetail?id=' + obj.id,
          })
        }

      } else {
        toast.show(res.errorMsg);
      }
    });
  },
  refresh: function () {
    session.login(this.refreshMe);
  },
  getPhoneNumber(e) {
    var that = this;
    console.log(e.detail.errMsg)
    console.log(e.detail.iv)
    console.log(e.detail.encryptedData);
    com.bindPhone(e, this, function () {
      that.refresh();

      if(that.data.obj.activityId) {
        that.gotoCut();
      } else {
        that.buy();
      }
    });
  },
  previewWorks: function (e) {
    biz.previewWorks(e, this)
  },
  getWorks() {
    var id = this.data.seller.id;
    var that = this;
    biz.getWorks(id, that);
  },
  gotoHome: function () {
    biz.gotoPage('/pages/index/index');
  },
})